





//
//  Canvers.m
//  touch 画图
//
//  Created by MB__Lee on 2018/5/8.
//  Copyright © 2018年 MB__Lee. All rights reserved.
//

#import "Canvers.h"

@interface Canvers()

@property(nonatomic,assign)CGPoint beginPoint;//记录起点的位置

@property(nonatomic,strong)UIBezierPath *bezerPath;//画图的贝塞尔曲线

@property(nonatomic,strong)NSMutableArray *pointsMut;//所有绘制点 存放的数组

@end

@implementation Canvers


-(void)awakeFromNib{//xib 加载之后会调用此方法
    [super awakeFromNib];
    
    
}
-(UIBezierPath *)bezerPath{
    if (!_bezerPath) {
        UIBezierPath *path = [UIBezierPath bezierPath];
        _bezerPath = path;
        
        path.lineWidth = self.lineWidth ? self.lineWidth : 5;
        path.lineCapStyle = kCGLineCapRound; //端点出的样式（圆端点，无样式，直角）
        path.lineJoinStyle = kCGLineJoinRound;//拐角处的样式（圆角，斜角，尖角）
    }
    return  _bezerPath;
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor grayColor];
        
    }
    return  self;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    //刚开始绘制，
    if ([self.delegate respondsToSelector:@selector(canverViewBeginPrint:)]) {
        [self.delegate canverViewBeginPrint:self];
    }
    
    
    if (_removeLastState) {
        [self.bezerPath removeAllPoints];//画完图之后的曲线--移除所有点
        [self.pointsMut removeAllObjects];//将存放点的数组清空
    }
    
    
    
    CGPoint point = [[touches anyObject] locationInView:self];//起始点的位置
    _beginPoint = point;//记录起始点
    
    
    [self.bezerPath moveToPoint:point];
    [self.pointsMut addObject:@(point)];
    
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGPoint point = [[touches anyObject] locationInView:self];//移动过程中经过点的位置
    
    [self.bezerPath addLineToPoint:point]; //将经过的点加到曲线上
    [self setNeedsDisplay];//进行重汇路径
    
    
    [self.pointsMut addObject:@(point)];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.bezerPath closePath];//将路径封闭
    [self setNeedsDisplay];//进行重汇路径
    
    if ([self.delegate respondsToSelector:@selector(canverViewEnPrint:sendAllPoints:)]) {
        [self.delegate canverViewEnPrint:self sendAllPoints:self.pointsMut];
    }
}
-(void)drawRect:(CGRect)rect{
    
//    [[UIColor redColor] setFill];
//    [self.bezerPath fill];//填充颜色
    
    
    if (_strokeColor) { //如果有颜色 的话，用自定义的颜色进行绘制
        [_strokeColor setStroke];
    }else{//默认颜色是随机色
     [[UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0] setStroke];
    }

    [self.bezerPath stroke];//填充线的颜色
    
}


#pragma mark --懒加载
-(NSMutableArray *)pointsMut{
    if (!_pointsMut) {
        _pointsMut = [NSMutableArray array];
    }
    return  _pointsMut;
}


@end
